package com.mediastory.spsserver.category.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mediastory.spsserver.category.domain.Category;
import com.mediastory.spsserver.category.service.CategorySvc;
import com.mediastory.spsserver.customer.service.CustomerSvc;

/**
 * @author Jaewon Choi
 */

@Controller
@RequestMapping(value={"/category"})
public class CategoryCtrl {
	
	private final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private CategorySvc categorySvc;
	
	@Autowired
	private CustomerSvc customerSvc;

	/**
	 * 목록 보기
	 * */
	@RequestMapping(value={"/list.do"})
	public Map<String, Object> list(HttpServletRequest request, HttpSession session) throws Exception {
		Map<String, Object> condition = new HashMap<String, Object>();
		//검색 parameter
		String name = ServletRequestUtils.getStringParameter(request, "name");
		condition.put("name", name);
		
		//customerIdx
		//Integer cIdx = (Integer)session.getAttribute("cIdx");
		//condition.put("cIdx", cIdx);
		
		//페이징 처리 parameter
		int maxnum = ServletRequestUtils.getIntParameter(request, "maxnum", 10);
		int page = ServletRequestUtils.getIntParameter(request, "page", 1);
		condition.put("maxnum", maxnum);
		condition.put("page", (page-1)*maxnum);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.putAll(categorySvc.findbyListPaging(condition));
		resultMap.put("maxnum", maxnum);
		resultMap.put("page", page);
		
		return resultMap;
	}
	
	/**
	 * 상세보기
	 * */
	@RequestMapping(value={"/detail.do"})
	public Map<String, Object> detail(@RequestParam(required=true, value="idx")  Integer idx) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		resultMap.put("category", categorySvc.findby(idx));
		
		return resultMap;
	}
	
	/**
	 * 등록,수정 폼
	 * */
	@RequestMapping(value={"/form.do"})
	public Map<String, Object> form(HttpServletRequest request) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
		
		resultMap.put("customerList", customerSvc.findbyList(condition));

		int idx = ServletRequestUtils.getIntParameter(request, "idx", 0);
		if(idx != 0){
			resultMap.put("category", categorySvc.findby(idx));
		}
		
		return resultMap;
	}
	
	/**
	 * 등록/수정
	 * */
	@RequestMapping(value={"/submit.do"}, method=RequestMethod.POST)
	public String submit(Category category, HttpSession session, HttpServletRequest request) throws Exception {
		String userId = (String)session.getAttribute("userId");
		String ip = request.getRemoteAddr();
		//customerIdx
		Integer cIdx = (Integer)session.getAttribute("cIdx");

		if(category.getIdx() != null){
			category.setModifiedId(userId);
			category.setModifiedIp(ip);
			categorySvc.modify(category);
		}else{
			category.setCreatedId(userId);
			category.setCreatedIp(ip);
			category.setcIdx(cIdx);
			categorySvc.add(category);
		}

		return "category/result";
	}
	
	/**
	 * 삭제
	 * */
	@RequestMapping(value={"/remove.do"}, method=RequestMethod.POST)
	public String remove(HttpServletRequest request) throws Exception {
		
		String ip = request.getRemoteAddr();
		int[] idx = ServletRequestUtils.getIntParameters(request, "idx");
		
		Map<String, Object> condition = new HashMap<String, Object>();
		
		condition.put("modifiedId", request.getUserPrincipal().getName());
		condition.put("modifiedIp", ip);
		condition.put("idx", idx);
		
		categorySvc.remove(condition);
		return "category/result";
	}

	/**
	 * 중복 체크
	 * */
	@RequestMapping(method=RequestMethod.POST, value="/chkDupl")
	public @ResponseBody Map<String, Object> chkDupl(HttpSession session, @RequestParam(required=true, value="idx")  Integer idx, @RequestParam(required=true, value="chkName")  String name) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("idx", idx);
			condition.put("chkName", name);

			String result = categorySvc.findbyChkDupl(condition);
			
			resultMap.put("resultCode", "200");
			resultMap.put("result", result);
		} catch (Exception e) {
			// TODO: handle exception
			//e.printStackTrace();
			logger.error(e.getMessage(), e);
			resultMap.put("resultCode", "500");
			resultMap.put("errMsg", "Error");
		}

		return resultMap;
	}
	
	/**
	 * 카테고리 편집 보기
	 * */
	@RequestMapping(value={"/order.do"})
	public Map<String, Object> order(HttpServletRequest request, HttpSession session) throws Exception {
		Map<String, Object> condition = new HashMap<String, Object>();
		//검색 parameter
		Integer categoryIdx = ServletRequestUtils.getIntParameter(request, "categoryIdx");
		condition.put("categoryIdx", categoryIdx);
		
		//customerIdx
		Integer cIdx = (Integer)session.getAttribute("cIdx");
		condition.put("cIdx", cIdx);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//resultMap.put("categoryList", categorySvc.findbyList(null));
		resultMap.put("categoryList", categorySvc.findbyList(condition));
		return resultMap;
	}
	
	/**
	 * 카테고리 내외 순서 목록 json
	 * */
	@RequestMapping(method=RequestMethod.GET, value="/dispOrderList/{categoryIdx}", headers="Accept=application/json")
	public @ResponseBody Map<String, Object> getDispOrderList(@PathVariable Integer categoryIdx, HttpSession session) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Integer cIdx = (Integer)session.getAttribute("cIdx");
			
			resultMap.put("resultCode", "200");
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("cIdx", cIdx);
			condition.put("categoryIdx", categoryIdx);
			resultMap.put("inCont", categorySvc.findbyListInCont(condition));
			resultMap.put("outCont", categorySvc.findbyListOutCont(condition));
		} catch (Exception e) {
			// TODO: handle exception
			//e.printStackTrace();
			logger.error(e.getMessage(), e);
			resultMap.put("resultCode", "500");
			resultMap.put("errMsg", "Error");
		}

		return resultMap;
	}

	/**
	 * 카테고리 순서 등록/수정
	 * */
	@RequestMapping(value={"/dispOrder/submit.do"}, method=RequestMethod.POST)
	public String submit(HttpServletRequest request, HttpSession session) throws Exception {
		
		Integer cIdx = (Integer)session.getAttribute("cIdx");
		
		int categoryIdx = ServletRequestUtils.getRequiredIntParameter(request, "categoryIdx");
		int[] dispOrderList = ServletRequestUtils.getIntParameters(request, "dispOrder");
		
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("cIdx", cIdx);
		condition.put("categoryIdx", categoryIdx);
		condition.put("dispOrderList", dispOrderList);
		
		categorySvc.addDispOrder(condition);
		
		return "redirect:/category/order.do?categoryIdx="+categoryIdx;
	}
	
}